package com.example.community.controller;
import com.example.community.entity.*;
import com.example.community.event.EventProducer;
import com.example.community.service.CommentService;
import com.example.community.service.DiscussPostService;
import com.example.community.service.LikeService;
import com.example.community.service.UserService;
import com.example.community.util.CommunityConstant;
import com.example.community.util.CommunityUtil;
import com.example.community.util.HostHolder;
import com.example.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @Author: huang
 * @Date: 2021/9/21 12:43
 * @Description:
 */
@Controller
@RequestMapping("/discuss")
public class DiscussPostController implements CommunityConstant {

    @Autowired
    private LikeService likeService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private UserService userService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    //发布帖子
    @RequestMapping(path = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        //先获取当前用户
        User user = hostHolder.getUser();
        System.out.println(user.toString());
        if (user == null) {
            //403无权限
            return CommunityUtil.getJSONString(403, "您还没有登陆!");
        }

        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        post.setType(0);
        post.setStatus(0);
        post.setCreateTime(new Date());
        post.setCommentCount(0);
        discussPostService.addDiscussPost(post);

        // 触发发帖事件
        Event event = new Event()
                .setUserId(user.getId())
                .setTopic(TOPIC_PUBLISH)
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(post.getId());
        eventProducer.fireEvent(event);

        //计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, post.getId());

        return CommunityUtil.getJSONString(0, "发布成功!");
    }

    //根据帖子ID点击帖子进入.用model携带数据发给模板
    @RequestMapping(path = "/detail/{discussPostId}", method = RequestMethod.GET)
    public String getDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model, Page page) {
        //根据帖子id找整个帖子信息
        DiscussPost post = discussPostService.findDiscussPostById(discussPostId);
        //将帖子信息给model
        model.addAttribute("post", post);

        //获取该帖子用户信息
        User user = userService.findUserById(post.getUserId());
        model.addAttribute("user", user);

        //点赞数量
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeCount", likeCount);

        //点赞状态，用户是否给帖子点过赞。如果用户没登陆返回0
        int likeStatus = hostHolder.getUser() == null ? 0 :
                likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeStatus", likeStatus);

        //设置评论的分页信息
        page.setLimit(5);
        page.setPath("/discuss/detail/" + discussPostId);
        page.setRows(post.getCommentCount());

        //评论：给帖子的评论
        //回复：给评论的评论

        //评论列表:
        /**
         * ENTITY_TYPE_POST : 评论的类型，对帖子的评论
         * post.getId() : 帖子的id
         */
        List<Comment> commentList = commentService.findCommentsByEntity(
                ENTITY_TYPE_POST, post.getId(), page.getOffset(), page.getLimit());

        //我们遍历 commentList 集合，我们构造一个 Map， 把Comment存进去，把我们查到的依赖的数据也存进去
        //评论Vo列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                //评论Vo
                Map<String, Object> commentVo = new HashMap<>();
                //把评论装入commentVo
                commentVo.put("comment", comment);
                //把评论的用户放入
                commentVo.put("user", userService.findUserById(comment.getUserId()));

                //点赞数量
                likeCount = likeService.findEntityLikeCount(ENTITY_TYPR_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);

                //点赞状态，用户是否给帖子点过赞。如果用户没登陆返回0
                likeStatus = hostHolder.getUser() == null ? 0 :
                        likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPR_COMMENT, comment.getId());
                commentVo.put("likeStatus", likeStatus);

                //在评论后可能还有别的用户回复
                //回复列表
                /**
                 * ENTITY_TYPR_COMMENT : 类型是评论
                 * comment.getId() ： 这条评论的id
                 * 0 - Integer.MAX_VALUE ： 把此条评论下的回复全部显示
                 */
                List<Comment> replyList = commentService.findCommentsByEntity(
                        ENTITY_TYPR_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
                //回复Vo
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (replyVoList != null) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        //把回复装入replyVo
                        replyVo.put("reply", reply);
                        //把回复的用户装入
                        replyVo.put("user", userService.findUserById(reply.getUserId()));
                        //回复目标
                        User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                        replyVo.put("target", target);

                        //点赞数量
                        likeCount = likeService.findEntityLikeCount(ENTITY_TYPR_COMMENT, reply.getId());
                        replyVo.put("likeCount", likeCount);

                        //点赞状态，用户是否给帖子点过赞。如果用户没登陆返回0
                        likeStatus = hostHolder.getUser() == null ? 0 :
                                likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPR_COMMENT, reply.getId());
                        replyVo.put("likeStatus", likeStatus);

                        //把 回复视图 replyVo 放入 回复视图列表 replyVoList
                        replyVoList.add(replyVo);
                    }
                }
                //把 回复视图列表 replyVoList 放入 评论视图 commentVo
                commentVo.put("replys", replyVoList);
                //回复数量，每条评论旁边会显示回复数量
                int replyCount = commentService.findCommentCount(ENTITY_TYPR_COMMENT, comment.getId());
                commentVo.put("replyCount", replyCount);
                //把 评论视图 commentVo 放入评论视图列表 commentVoList
                commentVoList.add(commentVo);
            }
        }
        model.addAttribute("comments", commentVoList);
        return "/site/discuss-detail";
    }

    /**
     * @param id    帖子id
     * @return  置顶操作
     */
    @RequestMapping(path = "/top", method = RequestMethod.POST)
    @ResponseBody
    public String setTop(int id) {
        discussPostService.updateType(id, 1);

        //因为置顶操作改变了帖子，所以我们触发发帖事件。
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        return CommunityUtil.getJSONString(0);
    }



    /**
     * @param id    帖子id
     * @return  加精操作
     */
    @RequestMapping(path = "/wonderful", method = RequestMethod.POST)
    @ResponseBody
    public String setWonderful(int id) {
        discussPostService.updateStatus(id, 1);

        //因为加精操作改变了帖子，所以我们触发发帖事件。
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        //计算帖子分数
        String rediskey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(rediskey, id);

        return CommunityUtil.getJSONString(0);
    }

    /**
     *
     * @param id    帖子id
     * @return  删除操作
     */
    @RequestMapping(path = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String setDelete(int id) {
        discussPostService.updateStatus(id, 2);

        //因为删除操作改变了帖子，所以我们触发删帖事件。
        Event event = new Event()
                .setTopic(TOPIC_DELETE)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        return CommunityUtil.getJSONString(0);
    }

}

